package l.l.w.practice.EightQueens;

import java.util.Arrays;

/**
 * Created by llw on 2017/9/4.
 *
 * 用循环解决 8皇后问题
 */
public class EightQueensLoop {

    public int eightQueens(int num){
        int[] location = new int[num+1];
        int k =1;
        int count=0;
        while(k>0){
            location[k] = location[k]+1;
            while(location[k] <= num && !check(location,k)){
                location[k] = location[k]+1;
            }
            if(location[k] <=num){
                if(k==num){
                    System.out.println(Arrays.toString(location));
                    count++;
                }
                else{
                    k=k+1;
                }
            }else{
                location[k]=0;
                k=k-1;
            }
        }
        return count;
    }

    private boolean check(int[] location, int k) {
        for(int i = 1 ; i < k; ++i){
            if(Math.abs(i-k)==Math.abs(location[i]-location[k]) || location[i]==location[k])
                return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int num = 8;
        int count = new EightQueensLoop().eightQueens(num);
        System.out.println(count);
    }
}
